<script setup lang="ts">
import { type FormInstance, Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { updateUserBaseInfo } from '@/apis'
import { useForm } from '@/hooks'
import * as Regexp from '@/utils/regexp'
import { useUserStore } from '@/stores'

const { width } = useWindowSize()

const visible = ref(false)
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const formRef = ref<FormInstance>()
const { form } = useForm({
  name: userInfo.value.name,
  gender: userInfo.value.gender,
})

const rules: FormInstance['rules'] = {
  name: [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线,长度为2-32位' }],
}

// 重置
const reset = () => {
  formRef.value?.resetFields()
  form.name = userInfo.value.name
  form.gender = userInfo.value.gender
}

// 打开编辑
const edit = async () => {
  reset()
  visible.value = true
}

// 保存
const onSave = async () => {
  console.log('进入保存函数')
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  try {
    console.log('userinfo = ', userInfo)
    await updateUserBaseInfo(form)
    Message.success('修改成功')
    // 修改成功后，重新获取用户信息
    await userStore.refreshUserInfo()
    console.log('userInfo', userInfo)
    return true
  } catch {
    return false
  }
}

defineExpose({ open, edit })
</script>

<template>
  <a-modal
    v-model:visible="visible"
    title="修改基本信息"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 500 ? 500 : '100%'"
    draggable
    @ok="onSave"
    @close="reset"
  >
    <a-form ref="formRef" layout="vertical" :model="form" :rules size="medium">
      <a-card title="基础信息" :bordered="false" class="section">
        <a-form-item label="昵称" field="name">
          <a-input v-model.trim="form.name" placeholder="请输入昵称" :max-length="32" />
        </a-form-item>
        <a-form-item label="性别" field="gender">
          <DictSelect v-model="form.gender" type="radio" code="GenderEnum" />
        </a-form-item>
      </a-card>
    </a-form>
  </a-modal>
</template>

<style lang="less" scoped></style>
